package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.Handler;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("Interceptor拦截到请求{}", requestURI);
        //判断后端是否登录
        Long emp = (Long) request.getSession().getAttribute("emp");
        if (emp != null) {//登录则放行
            BaseContext.setCurrentId(emp);
            return true;
        }
        //判断前端是否登录
        Long user = (Long) request.getSession().getAttribute("user");
        if (user!=null){
            BaseContext.setCurrentId(user);
            return true;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
